package com.tjl.yangxixis.activity;


import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lyp.jsonbean.LoginBean;
import com.tjl.yangxixis.R;
import com.tjl.yangxixis.api.YangxixiApi;
import com.tjl.yangxixis.utils.ProgressDialogUtils;

import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import pl.droidsonroids.gif.GifImageView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 登录
 */
public class LoggingActivity extends FragmentActivity implements OnClickListener{
    private GifImageView mLoginimg;
    private EditText mUserName;
    private EditText mUserPwd;
    private Button mLogin;
    private String userName;
    private String userPwd;
    SPUtils sputils;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_logging);
        sputils = new SPUtils("login");
        initview();
        mUserName.setText(sputils.getString("name",""));
        //暂时记住密码
        mUserPwd.setText(sputils.getString("pwd",""));
        start();
    }

    private void initview(){
        mLoginimg = (GifImageView) findViewById(R.id.start_loginimg);
        mUserName = (EditText) findViewById(R.id.et_loginuserName);
        mUserPwd = (EditText) findViewById(R.id.et_loginuserpwd);
        mLogin = (Button) findViewById(R.id.btn_logins);
        mUserName.setOnClickListener(this);
        mUserPwd.setOnClickListener(this);
        mLogin.setOnClickListener(this);
//        Glide.with(LoggingActivity.this).load(R.drawable.gif)
//                .diskCacheStrategy(DiskCacheStrategy.ALL)
//                .into(mLoginimg);
    }

    //启动图
    private void start(){
        /**
         //		 * 五秒后隐藏启动图/显示登陆页
         //		 */
        int status = getIntent().getIntExtra("status", 0);
        if (status == 1) {
            mLoginimg.setVisibility(View.GONE);
        } else {
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    mLoginimg.setVisibility(View.GONE);
                }
            }, 1000);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        switch (arg0.getId()) {
            case R.id.btn_logins:
                try {
                    if (isNull()) {
                        // 判断网络是否连接并且是否可用
                        if (NetworkUtils.isConnected() && NetworkUtils.isAvailableByPing()) {
                        login();
                        } else {
                            ToastUtils.showShortSafe("当前网络不可用！");
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    public void login() throws IOException {
        ProgressDialogUtils.getInstance().builder(this).setCancelable(false).setCanCelMessage("登录已取消").show("正在登录中");
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(YangxixiApi.APP_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        YangxixiApi github = retrofit.create(YangxixiApi.class);
        Call<LoginBean> call = github.getLogin(userName, userPwd);
        call.enqueue(new Callback<LoginBean>() {
            @Override
            public void onResponse(Call<LoginBean> call, Response<LoginBean> response) {
                LoginBean bean = response.body();
                if (bean.getResult() == 1) {
                    ToastUtils.showShort(response.body().getMessage());
                    List<LoginBean.DataBean> dataBeen = bean.getData();
                    sputils.put("name",dataBeen.get(0).getUser());
                    //暂时记住密码
                    sputils.put("pwd",dataBeen.get(0).getPwd());
                    Intent intent = new Intent(LoggingActivity.this,MainActivity.class);
                    Bundle args = new Bundle();
                    args.putSerializable("dataBean", dataBeen.get(0));
                    intent.putExtras(args);

                    // 调用 Handler 来异步设置别名
                    Message msg = mHandler.obtainMessage();
                    msg.what = MSG_SET_ALIAS;
                    msg.arg1 = Integer.parseInt(dataBeen.get(0).getId()); // 设置别名
                    if (dataBeen.get(0).getManager().equals("1")) {
                        msg.arg2 = Integer.parseInt(dataBeen.get(0).getC_id()); // 设置标签
                    }
                    mHandler.sendMessage(msg);
                    startActivity(intent);
                    finish();
                }
                else {
                    ToastUtils.showShort("登录失败！请检查用户名或密码是否正确！");
                }
                ProgressDialogUtils.getInstance().dismiss();
            }
            @Override
            public void onFailure(Call<LoginBean> call, Throwable t) {
                ToastUtils.showShort(t.getMessage());
                ProgressDialogUtils.getInstance().dismiss();
            }
        });
    }

    //判断用户名和密码是否为空
    @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
    boolean isNull(){
        userName = mUserName.getText().toString();
        userPwd = mUserPwd.getText().toString();
        //判断用户名是否为空
        if (userName.isEmpty()){
            Toast.makeText(LoggingActivity.this,"请输入用户名",Toast.LENGTH_SHORT).show();
            return false;
        } else if(userPwd.isEmpty()){ //判断密码是否为空
            Toast.makeText(LoggingActivity.this,"请输入密码",Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs ;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    Log.i("tag", logs);
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Log.i("tag", logs);
                    // 延迟 60 秒来调用 Handler 设置别名
                    Message msg = mHandler.obtainMessage();
                    msg.what = MSG_SET_ALIAS;
                    msg.arg1 = Integer.parseInt(alias); // 设置别名
                    msg.arg2 = Integer.parseInt(tags.iterator().next()); // 设置标签
                    mHandler.sendMessageDelayed(msg, 1000 * 60);
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    Log.e("tag", logs);
            }
        }
    };
    private static final int MSG_SET_ALIAS = 1001;
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    Log.d("tag", "Set alias in handler.");
                    // 调用 JPush 接口来设置别名。
                    Set<String> set = new HashSet<>();
                    set.add(String.valueOf(msg.arg2));
                    JPushInterface.setAliasAndTags(getApplicationContext(),
                            String.valueOf(msg.arg1),
                            set,
                            mAliasCallback);
                    break;
                default:
                    Log.i("tag", "Unhandled msg - " + msg.what);
            }
        }
    };

//    //跳转到相对应的Fragment
//    private void setDefaultFragment(Fragment fragment){
//        fm = getSupportFragmentManager();
//        ft = fm.beginTransaction();
//        ft.add(R.id.frame, fragment);
//        //transaction.addToBackStack(null);
//        ft.commit();
//    }

}
